import { SetMetadata } from '@nestjs/common';

// 日志类型常量
export const LOG_TYPES = {
  ADMIN_OPERATION: 'admin_operation',
  LOGIN_LOG: 'login_log',
  SECURITY_EVENT: 'security_event',
  SYSTEM_EVENT: 'system_event',
} as const;

export type LogType = typeof LOG_TYPES[keyof typeof LOG_TYPES];

// 记录操作日志的装饰器
export const LogOperation = (
  operationType: string,
  targetType?: string,
  logType: LogType = LOG_TYPES.ADMIN_OPERATION,
) => SetMetadata('logOperation', { operationType, targetType, logType });

// 记录登录日志的装饰器
export const LogLogin = (
  operationType: string = 'login',
) => SetMetadata('logLogin', { operationType });

// 记录安全事件的装饰器
export const LogSecurity = (
  eventType: string,
  securityLevel: number,
  description?: string,
) => SetMetadata('logSecurity', { eventType, securityLevel, description });

// 辅助函数：从请求中提取IP地址
export const getClientIp = (request: any): string => {
  return (
    request.headers['x-forwarded-for'] ||
    request.headers['x-real-ip'] ||
    request.connection.remoteAddress ||
    request.socket.remoteAddress ||
    request.ip ||
    '127.0.0.1'
  );
};

// 辅助函数：从请求中提取设备信息
export const getDeviceInfo = (request: any): string => {
  const userAgent = request.headers['user-agent'] || '';
  
  if (userAgent.includes('Mobile')) {
    return 'Mobile';
  } else if (userAgent.includes('iPhone')) {
    return 'iPhone';
  } else if (userAgent.includes('Android')) {
    return 'Android';
  } else if (userAgent.includes('iPad')) {
    return 'iPad';
  } else {
    return 'Desktop';
  }
};

// 辅助函数：获取地理位置信息（这里可以接入真实的IP地理位置服务）
export const getLocation = async (ip: string): Promise<string> => {
  // 这里可以接入真实的IP地理位置API
  // 目前返回默认值，实际应用中需要替换为真实的地理位置服务
  const mockLocations = ['北京', '上海', '广州', '深圳', '杭州', '成都'];
  return mockLocations[Math.floor(Math.random() * mockLocations.length)];
};